require('dotenv').config({ path: './nestjs-app/.env' });
const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

// 技能数据（从Dictionary.js中提取）
const skillData = {
    1: {
        id: 1,
        type: 1,
        name: "舍身取义",
        side: 1,
        short: "舍",
        ani: "she-8"
    },
    3: {
        id: 3,
        type: 3,
        name: "血雨腥风",
        side: 1,
        short: "风",
        ani: "feng-6"
    },
    5: {
        id: 5,
        type: 2,
        name: "围点打援",
        side: 1,
        short: "围",
        ani: "wei-6"
    },
    8: {
        id: 8,
        type: 3,
        name: "煽风点火",
        side: 1,
        short: "火",
        ani: "huo-8"
    },
    9: {
        id: 9,
        type: 1,
        name: "劈头盖脸",
        side: 1,
        short: "劈",
        ani: "pi-8"
    },
    10: {
        id: 10,
        type: 1,
        name: "横扫一排",
        side: 1,
        short: "排",
        ani: "pai-8"
    },
    11: {
        id: 11,
        type: 2,
        name: "乱作一团",
        side: 1,
        short: "乱",
        ani: "luan-8"
    },
    12: {
        id: 12,
        type: 2,
        name: "千里冰封",
        side: 1,
        short: "封",
        ani: "feng-8"
    },
    13: {
        id: 13,
        type: 3,
        name: "天打雷劈",
        side: 1,
        short: "雷",
        ani: "lei-8"
    },
    14: {
        id: 14,
        type: 3,
        name: "罪恶毒心",
        side: 1,
        short: "毒",
        ani: "du-8"
    },
    15: {
        id: 15,
        type: 1,
        name: "坚如磐石",
        side: 2,
        short: "固",
        ani: "gu-8"
    },
    16: {
        id: 16,
        type: 2,
        name: "金蝉脱壳",
        side: 2,
        short: "脱",
        ani: "tuo-8"
    },
    17: {
        id: 17,
        type: 3,
        name: "毁天灭地",
        side: 1,
        short: "灭",
        ani: "hui-8"
    },
    18: {
        id: 18,
        type: 2,
        name: "隐姓埋名",
        side: 2,
        short: "暗",
        ani: "yin-8"
    },
    19: {
        id: 19,
        type: 1,
        name: "凌波微步",
        side: 2,
        short: "速",
        ani: "ling-8"
    },
    101: {
        id: 101,
        type: 0,
        name: "禁法",
        side: 1,
        short: "禁",
        ani: "feng-6"
    },
    102: {
        id: 102,
        type: 0,
        name: "眩晕",
        side: 1,
        short: "晕",
        ani: "feng-6"
    },
    103: {
        id: 103,
        type: 0,
        name: "力竭",
        side: 1,
        short: "竭",
        ani: "feng-6"
    }
};

// 技能类型映射
const skillTypeMap = {
    0: '特殊状态',
    1: '武士',
    2: '文人', 
    3: '异师'
};

// 技能方向映射
const skillSideMap = {
    1: '攻击',
    2: '防御'
};

async function importSkillBaseData() {
    console.log('🚀 开始导入技能基础数据...');

    const connection = await mysql.createConnection({
        host: process.env.DB_HOST,
        user: process.env.DB_USER,
        password: process.env.DB_PASS,
        database: process.env.DB_NAME,
        port: parseInt(process.env.DB_PORT || '3306', 10),
        waitForConnections: true,
        connectionLimit: 10,
        queueLimit: 0,
        acquireTimeout: 60 * 1000, // 60 seconds
        timeout: 60 * 1000 // 60 seconds
    });

    try {
        await connection.connect();
        console.log('✅ 数据库连接成功！');

        // 检查表是否存在
        const [rows] = await connection.execute("SHOW TABLES LIKE 'skill_base'");
        if (rows.length === 0) {
            console.error('❌ skill_base 表不存在，请先创建表结构。');
            return;
        }
        console.log('✅ skill_base 表存在');

        const skillEntries = Object.values(skillData);
        console.log(`📊 找到 ${skillEntries.length} 个技能数据`);

        // 清空现有数据
        console.log('🗑️ 清空现有技能基础数据...');
        await connection.execute('DELETE FROM skill_base');
        console.log('✅ 现有数据已清空');

        // 导入新数据
        console.log('📥 开始导入技能基础数据...');

        const insertSql = `
            INSERT INTO skill_base (
                id, name, type, side, short, ani, skill_descr, created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
        `;

        let successCount = 0;
        let errorCount = 0;

        for (const skill of skillEntries) {
            try {
                // 生成技能描述
                const skillDescr = `${skill.name} - ${skillTypeMap[skill.type]}系${skillSideMap[skill.side]}技能`;

                const values = [
                    skill.id,
                    skill.name,
                    skill.type,
                    skill.side,
                    skill.short,
                    skill.ani,
                    skillDescr
                ];

                await connection.execute(insertSql, values);
                console.log(`✅ 导入技能: ${skill.name} (ID:${skill.id}, 类型:${skillTypeMap[skill.type]}, 方向:${skillSideMap[skill.side]})`);
                successCount++;

            } catch (error) {
                console.error(`❌ 导入技能失败: ${skill.name} (ID:${skill.id})`, error.message);
                errorCount++;
            }
        }

        console.log('\n📊 导入结果统计:');
        console.log(`✅ 成功导入: ${successCount} 条记录`);
        console.log(`❌ 导入失败: ${errorCount} 条记录`);
        console.log(`📈 总计处理: ${skillEntries.length} 条记录`);

        console.log('\n🔍 验证导入结果...');
        const [countRows] = await connection.execute('SELECT COUNT(*) AS count FROM skill_base');
        console.log(`📊 数据库中现有技能数量: ${countRows[0].count}`);

        // 按类型统计
        const [typeDistribution] = await connection.execute('SELECT type, COUNT(*) as count FROM skill_base GROUP BY type ORDER BY type ASC');
        console.log('\n📈 技能类型分布:');
        typeDistribution.forEach(row => {
            console.log(`  ${skillTypeMap[row.type] || `未知类型(${row.type})`}: ${row.count} 个技能`);
        });

        // 按方向统计
        const [sideDistribution] = await connection.execute('SELECT side, COUNT(*) as count FROM skill_base GROUP BY side ORDER BY side ASC');
        console.log('\n📈 技能方向分布:');
        sideDistribution.forEach(row => {
            console.log(`  ${skillSideMap[row.side] || `未知方向(${row.side})`}: ${row.count} 个技能`);
        });

        console.log('\n📋 部分技能信息:');
        const [sampleSkills] = await connection.execute(`
            SELECT id, name, type, side, short, ani
            FROM skill_base
            ORDER BY type ASC, id ASC
            LIMIT 10
        `);
        sampleSkills.forEach(skill => {
            console.log(`  ${skill.id}. ${skill.name} (${skillTypeMap[skill.type]}, ${skillSideMap[skill.side]}) - ${skill.short}`);
        });

        console.log('\n🎉 技能基础数据导入完成！');

    } catch (error) {
        console.error('❌ 导入过程中发生错误:', error.message);
    } finally {
        await connection.end();
        console.log('🔌 数据库连接已关闭');
        console.log('✅ 脚本执行完成');
    }
}

importSkillBaseData();
